from datetime import datetime
from super.super import *
from mail.mail import *
class Php(object):
    def get_sid(self,uid):
        sql=Mysql()
        sql.db_connect()
        sql.select_db('yln_sid')
        data=sql.select_one({'uid':uid})
        self.uid=uid
        self.sid=data['sid']
        self.pwd=data['pwd']
        print(self.sid,self.pwd)
        self.site = ''
        if data['site']!='':
            self.site="http://"+str(data['site'])+"/"
        return data

    def get_grade_data(self,year='',term=''):

        if self.site!='':
            a=Get_info(self.sid,self.pwd,self.site)
        else:
            a=Get_info(self.sid,self.pwd)
        if year=='':
            year=datetime.now().year
            year=str(year)
        if term=='':
            term='all'
        self.data=a.get_grade_info(year,term)
        return self.data

    def insert_grade_data(self):
        db = Mysql()
        db.db_connect()
        data_list=[]
        for single_data in self.data:
            class1=single_data['课程名称']
            score=single_data['成绩']
            year=single_data['考核学年']
            term=single_data['考核学期']
            get_time=single_data['统计时间']
            uid=self.uid
            jd=single_data['绩点']
            xf=single_data['学分']
            data_dict={
                'class':class1,
                'score':score,
                'year':year,
                'term':term,
                'get_time':get_time,
                'uid':uid,
                'jd':jd,
                'xf':xf
            }
            db.select_db('yln_grade')
            if not(db.select_one({'class':class1,'year':year,'term':term,'uid':uid})):
                db.insert_data_one(data_dict)
                data_list.append(data_dict)
        db.select_db('yln_user')
        user = db.select_one({'Id': self.uid})
        receiver_mail = user['mail']
        receiver_name = user['name']
        msg = ''
        for data_one in data_list:
            for key in data_one:
                msg += str(key) + ':' + str(data_one[key]) + '\n'
            msg+='------------------------------\n'
        mail = Mail()
        mail.set_basedata(receivers=[receiver_mail])
        mail.set_msg(msg, to_=receiver_name)
        print(data_list)
        if data_list:
            mail.send()


    def get_all_grade(self,year='2020',term='1'):
        sql=Mysql()
        sql.db_connect()
        sql.select_db('yln_sid')
        datas=sql.select_all()
        for data in datas:
            self.get_sid(data['uid'])
            self.get_grade_data(year,term)
            self.insert_grade_data()



